package com.example.wan1.view.todo;

import android.app.Dialog;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.adapter.TodoAdapter;
import com.example.wan1.base.activity.SimpleActivity;
import com.example.wan1.bus.RxBus;
import com.example.wan1.constant.Constants;
import com.example.wan1.event.NotifyOperateEvent;
import com.example.wan1.model.TodoBean;
import com.example.wan1.model.common.CommonResList;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.scwang.smart.refresh.footer.BallPulseFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import butterknife.BindView;
import butterknife.ButterKnife;

public class TodoActivity extends SimpleActivity implements TodoContract.View,
        OnLoadMoreListener, OnRefreshListener {

    @BindView(R.id.srlheader)
    MaterialHeader mSrlheader;
    @BindView(R.id.todo_rv)
    RecyclerView mTodoRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.todo_tabr)
    Toolbar mToolbar;

    @Inject
    TodoAdapter mAdapter;
    @Inject
    List<TodoBean> mList;
    @Inject
    TodoPresenter mPresenter;

    private int page = 1;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_todo;
    }

    @Override
    protected void initData() {
        mPresenter.todoList(page, 0, 0, 0, 0);
    }

    @Override
    protected void initView() {
        initTbar();

        //mList = new ArrayList<>();
        //mAdapter = new TodoAdapter(R.layout.todo_item, mList);
        mTodoRv.setAdapter(mAdapter);
        mTodoRv.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        mTodoRv.setNestedScrollingEnabled(false);
        mTodoRv.setHasFixedSize(true);

        //mSrlheader.setColorSchemeResources(R.color.qc_green);
        mSrlheader.setColorSchemeResources(ToolsUtils.getAttrId(this));

        mSrl.setOnLoadMoreListener(this);
        mSrl.setOnRefreshListener(this);

        mSrl.setEnableRefresh(false);
        mSrl.setEnableLoadMore(false);

        mAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            TodoDialogFragment.newInstance(Constants.EDIT_TODO, mList.get(i)).show(getSupportFragmentManager(), "todo_dialogfragment");
        });

        mAdapter.setOnItemChildClickListener((baseQuickAdapter, view, i) -> {
            switch (view.getId()) {
                case R.id.item_todo_more:
                    // 底部弹出对话框
                    Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
                    View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_handle_todo, null);
                    bottomDialog.setContentView(contentView);
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
                    params.width = getResources().getDisplayMetrics().widthPixels - ToolsUtils.dp2px(16);
                    params.bottomMargin = ToolsUtils.dp2px(8);
                    contentView.setLayoutParams(params);
                    bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
                    bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);

                    /*if (mList.get(i).getStatus() == 0) {
                        contentView.findViewById(R.id.done_todo).setVisibility(View.VISIBLE);
                    }*/
                    bottomDialog.show();
                    // 点击对话框中编辑
                    contentView.findViewById(R.id.edit_todo).setOnClickListener(v1 -> {
                        bottomDialog.dismiss();
                        TodoDialogFragment.newInstance(Constants.EDIT_TODO, mList.get(i)).show(getSupportFragmentManager(), "todo_dialogfragment");
                    });

                    // 点击对话框删除
                    contentView.findViewById(R.id.delete_todo).setOnClickListener(v1 -> {
                        TodoHandleTool.getInstance().deleteTodo(mList.get(i).getId());
                        bottomDialog.dismiss();
                    });

                    // 点击完成该ToDo
                    contentView.findViewById(R.id.done_todo).setVisibility(View.VISIBLE);
                    TextView tv = contentView.findViewById(R.id.done_todo);
                    TodoBean todoBean = mList.get(i);
                    tv.setText(todoBean.getStatus() == 1 ? getString(R.string.todo_cancel_done) : getString(R.string.todo_done));
                    contentView.findViewById(R.id.done_todo).setOnClickListener(v1 -> {
                        /*ImageView iv = view.findViewById(R.id.item_todo_more);
                        CardView cardView = view.findViewById(R.id.item_todo_cardview);
                        TodoBean todoBean = mList.get(i);
                        if (todoBean.getStatus() == 1) {
                            iv.setImageResource(R.drawable.todo_not_done);
                            todoBean.setStatus(0);
                            TodoHandleTool.getInstance().updateTodoStatus(mList.get(i).getId(), 0);
                        } else {
                            iv.setImageResource(R.drawable.todo_done);
                            todoBean.setStatus(1);
                            TodoHandleTool.getInstance().updateTodoStatus(mList.get(i).getId(), 1);
                        }
                        mAdapter.notifyItemChanged(i);*/
                        TodoHandleTool.getInstance().updateTodoStatus(mList.get(i).getId(),
                                todoBean.getStatus() == 1 ? 0 : 1);

                        bottomDialog.dismiss();
                    });
            }
        });

        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary,
                typedValue, true);

        View footer = LayoutInflater.from(this).inflate(R.layout.empty_item, mSrl, false);
        ImageView iv = footer.findViewById(R.id.empty_iv);
        iv.setColorFilter(typedValue.data);
        mAdapter.setEmptyView(footer);

        int color = ToolsUtils.getThemeColor(this);
        if (color != 0) {
            mToolbar.setBackgroundColor(color);
            StatusBarUtil.setColor(this, color, 0);
            iv.setColorFilter(color);

            mSrlheader.setColorSchemeColors(color);
            BallPulseFooter mFooter = findViewById(R.id.srlfooter);
            if (mFooter != null) {
                mFooter.setNormalColor(color);
                mFooter.setAnimatingColor(color);
            }
        }
        if (ToolsUtils.getNightMode(this))
            StatusBarUtil.setTransparent(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onSuccess(CommonResList<TodoBean> data) {
        hideLoading();
        if (data.getDatas().size() > 0) {
            mSrl.setEnableRefresh(true);
            mSrl.setEnableLoadMore(true);
        }
        if (data.isOver() && data.getDatas().size() > 0) {
            mAdapter.loadMoreEnd();
            if (mAdapter.getFooterLayoutCount() == 0) {
                View footer = LayoutInflater.from(this).inflate(R.layout.loadmore_view, null);
                mAdapter.addFooterView(footer);
            }
            mSrl.setEnableLoadMore(false);
        }

        if (data.getDatas().size() == 0) {
            if (mAdapter.getData().size() > 0)
                mAdapter.notifyDataSetChanged();
            mAdapter.isUseEmpty(true);
        } else {
            mAdapter.isUseEmpty(false);
        }

        page = data.getCurPage() + 1;
        mAdapter.addData(data.getDatas());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(String msg) {
        ToastUtils.showToast(msg);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mTodoRv.postDelayed(() -> {
            mPresenter.todoList(page, 0, 0, 0, 0);
            mSrl.finishLoadMore(true);
        }, 200);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mList.clear();
        mTodoRv.postDelayed(() -> {
            mPresenter.todoList(1, 0, 0, 0, 0);
            mSrl.finishRefresh(true);
        }, 200);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.add_item:
                //打开增加todo的界面
                mAdapter.isUseEmpty(false);
                mAdapter.notifyDataSetChanged();
                TodoDialogFragment.newInstance(Constants.ADD_TODO).show(getSupportFragmentManager(), "todo_dialogfragment");
                break;
            case R.id.menu_item_priority_important:
                filterData(0, 0, 0, 1);
                break;
            case R.id.menu_item_priority_normal:
                filterData(0, 0, 0, 2);
                break;
            case R.id.menu_item_type_work:
                filterData(0, 1, 0, 0);
                break;
            case R.id.menu_item_type_study:
                filterData(0, 2, 0, 0);
                break;
            case R.id.menu_item_type_play:
                filterData(0, 3, 0, 0);
                break;

            case R.id.menu_item_status_done_z1:
                //filterData(1, 0, 0, 1);
                filterDataOrder(1, 1);
                break;
            case R.id.menu_item_status_done_z2:
                //filterData(1, 0, 0, 3);
                filterDataOrder(1, 3);
                break;
            case R.id.menu_item_status_done_d1:
                //filterData(1, 0, 0, 2);
                filterDataOrder(1, 2);
                break;
            case R.id.menu_item_status_done_d2:
                //filterData(1, 0, 0, 4);
                filterDataOrder(1, 4);
                break;

            case R.id.menu_item_status_not_done_z1:
                //filterData(0, 0, 0, 3);
                filterDataOrder(0, 3);
                break;
            case R.id.menu_item_status_not_done_d1:
                //filterData(0, 0, 0, 4);
                filterDataOrder(0, 4);
                break;
            case R.id.menu_item_status_all_z1:
                filterDataOrder(3);
                break;
            case R.id.menu_item_status_all_d1:
                filterDataOrder(4);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void initTbar() {
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        RxBus.getDefault().subscribe(this, new RxBus.Callback<NotifyOperateEvent>() {
            @Override
            public void onEvent(NotifyOperateEvent event) {
                if ("todo".equals(event.getType())) {
                    mList.clear();
                    //mPresenter.todoList(1, 0, 0, 0, 0);
                    mPresenter.todoListAll(1);//加载全部
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    public void filterData(int status, int type, int orderby, int priority) {
        //type 0全部1工作2学习3娱乐
        //priority 1重要2一般
        //status 0未完成1完成
        mList.clear();
        mPresenter.todoList(1, status, type, orderby, priority);
    }

    public void filterDataOrder(int orderby) {
        mList.clear();
        mPresenter.todoListOrderAll(1, orderby);
    }

    public void filterDataOrder(int status, int orderby) {
        mList.clear();
        mPresenter.todoListOrder(1, status, orderby);
    }
}
